package com.lisp.algorithm.sort;

import com.lisp.algorithm.util.SortUtil;

public class QuickSort {
    
    public static void main(String[] args) {        
        SortUtil.test(QuickSort::sort);
    }
    
    public static void sort(int a[]) {
        sortSpaceOptimized(a, 0, a.length);
    }

    public static void sort(int a[], int start, int end) {
        if(start < end-1) {
            int p = partition(a, start, end);
            sort(a, start, p+1);
            sort(a, p+1, end);
        }
    }
    
    public static void sortSpaceOptimized(int a[], int start, int end) {
        while(start < end-1) {
            int p = partition(a, start, end);
            if(p < (start+end)/2) {
                sortSpaceOptimized(a, start, p+1); // 递归左半边
                start = p+1;                // 迭代右半边
            } else {
                sortSpaceOptimized(a, p+1, end); // 递归右半边
                end = p+1;                  // 迭代左半边
            }
        }
    }
    
    public static int partition(int a[], int start, int end) {
        int pivot = a[start];
        int i = start-1;
        int j = end;
        
        while(true) {
            do {
                i++;
            } while(a[i] < pivot);
            
            do {
                j--;
            } while(a[j] > pivot);
            
            if(i < j) {
                SortUtil.swap(a, i, j);
            } else {
                return j;
            }
        }
    }
}
